var action = 'add';

$('#btnAdd').click(function () {
    var msg = '';
    if (action === 'modify') {
        msg = '修改数据';
    } else if (action === 'add') {
        msg = '添加数据';
    }
    $.ajax({
        url: '/student/' + action,
        method: 'post',
        data: $('#frmAppend').serialize()
    }).then(res => {
        console.log(res);
        if (res.code === 0) {
            alert(msg + '成功！');
            window.location.href = '/student';
        } else {
            alert(msg + '失败！');
        }
    });
});

function del(sNo) {
    // alert('删除编号为【' + sNo + '】的学生信息');
    $.ajax({
        url: '/student/del',
        method: 'post',
        data: 'sNo=' + sNo
    }).then(res => {
        console.log(res);
        if (res.code === 0) {
            alert('删除数据成功！');
            window.location.href = '/student';
        } else {
            alert('删除数据失败！');
        }
    });
}

// 添加学生信息
$('h1 > span.btn').click(function(){

    action = 'add';
    $('input[name=sNo]').val('');
    $('input[name=sName]').val('');
    $('input[name=sBirthday]').val('');
    $('select[name=class]').val('')
    $('#btnAdd').val('添加学生');
    $('#frmAppend h2').html('学生信息录入')
    $('#mask').show();
});

// 修改学生信息
function modify(stu) {
    // console.log(stu);
    $('input[name=sNo]').val(stu.sNo);
    $('input[name=sName]').val(stu.sName);
    $('input[name=sBirthday]').val(stu.sBirthday.substr(0, 10));
    $('select[name=class]').val(stu.class)
    var radios = $('input[name=sSex]');
    // console.log(radios);
    for (var radio of radios) {
        radio.checked = (radio.value === stu.sSex);
    }
    action = 'modify';
    $('#btnAdd').val('修改信息');
    $('#frmAppend h2').html('修改学生信息')
    $('#mask').show();
}

$('p > span.btn').click(function(){
    $('#mask').hide();
});

$('span#filterClass > select').change(function(){
    // alert('筛选' + $(this).val() + '的学生');
    $.ajax({
        url: '/student/filter',
        method: 'post',
        data: 'class=' + $(this).val()
    }).then(res => {
        // console.log(res);
        document.getElementById('stuList').outerHTML = res;
    });

});
